﻿using Microsoft.AspNetCore.Components.Server.Circuits;

namespace BlazorApp4.Service
{
    public class TrackingCircuitHandler: CircuitHandler
    {
        private HashSet<Circuit> _circuits = new HashSet<Circuit>();
        /// <summary>
        /// Invoked when a new circuit was established.
        /// </summary>
        /// <param name="circuit">The <see cref="Circuit"/>.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> that notifies when the client connection is aborted.</param>
        /// <returns><see cref="Task"/> that represents the asynchronous execution operation.</returns>
        public override Task OnCircuitOpenedAsync(Circuit circuit, CancellationToken cancellationToken)
        {
            Console.WriteLine("OnCircuitOpenedAsync");
            return Task.CompletedTask;

        }
        public override Task OnConnectionUpAsync(Circuit circuit,
            CancellationToken cancellationToken)
        {
            Console.WriteLine("OnConnectionUpAsync");
            _circuits.Add(circuit);
            return Task.CompletedTask;
        }
        public override Task OnConnectionDownAsync(Circuit circuit,
            CancellationToken cancellationToken)
        {
            Console.WriteLine("OnConnectionDownAsync");
            _circuits.Remove(circuit);
            return Task.CompletedTask;
        }

        /// <summary>
        /// Invoked when a new circuit is being discarded.
        /// </summary>
        /// <param name="circuit">The <see cref="Circuit"/>.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
        /// <returns><see cref="Task"/> that represents the asynchronous execution operation.</returns>
        public override Task OnCircuitClosedAsync(Circuit circuit, CancellationToken cancellationToken)
        {
            Console.WriteLine("OnCircuitClosedAsync");

            return Task.CompletedTask;
        }
        public int ConnectedCircuits => _circuits.Count;
    }
}
